const { Router } = require("express");
const JWT = require("jsonwebtoken");
const User = require("../model/User");
const Cart = require("../model/Cart");
const Order = require("../model/Order");
const WaitPay = require("../model/WaitPay");

const router = new Router();
// 登录了才能操作
// 中间件，用于处理是否登录了，设置了一道令牌
router.use(async (req, res, next) => {
    try {
        const token = req.headers["authorization"].replace("Bearer ", "");
        const result = JWT.verify(token, "hello world");
        const user = await User.findById(result._id);
        if (user) {
            req.userInfo = user;
            next();
        } else {
            throw new Error("用户不存在");
        }
    } catch (error) {
        res.json({ code: -1, message: "请重新登录" });
    }
});

router.post("/submit_order", async (req, res) => {
    const rest = req.fetchBody;
    console.log(rest);
    try {
        // 先查找再插入
        rest.forEach(async (item) => {
            const result = await Order.findOne({
                selectedIDs: item.selectedIDs,
            });
            if (result) {
                await Order.updateOne(
                    { selectedIDs: item.selectedIDs },
                    { count: item.count + result.count }
                );
            } else {
                const {
                    goodsID,
                    goodsName,
                    goodsImg,
                    count,
                    selected,
                    selectedIDs,
                    counterPrice,
                    retailPrice,
                } = await Cart.findOne({ selectedIDs: item.selectedIDs });
                await new Order({
                    goodsID,
                    goodsName,
                    goodsImg,
                    user: req.userInfo._id,
                    count,
                    selected,
                    selectedIDs,
                    counterPrice,
                    retailPrice,
                    flag: item.flag,
                    date: item.date,
                }).save();
            }
        });
        res.json({ code: 0, message: "ok" });
    } catch (error) {
        res.json({ code: -1, message: "ok" });
    }
});
router.get("/get_cart_order", async (req, res) => {
    const result = await Order.find({ flag: 0 });
    if (result) {
        res.json({ code: 0, message: "ok", data: result });
    } else {
        res.json({ code: -1, message: "读取失败" });
    }
});
router.post("/modify_goods_flag", async (req, res) => {
    const rest = req.fetchBody;
    rest.forEach(async (item) => {
        await new WaitPay({
            goodsID: item.goodsID,
            goodsName: item.goodsName,
            goodsImg: item.goodsImg,
            user: req.userInfo._id,
            count: item.count,
            selected: item.selected,
            selectedIDs: item.selectedIDs,
            counterPrice: item.counterPrice,
            retailPrice: item.retailPrice,
            flag: 1,
            date: item.date,
        }).save();
    });
    rest.forEach(async (item) => {
        await Order.findOneAndDelete({
            selectedIDs: item.selectedIDs,
        });
    });

    res.json({ code: 0, message: "ok" });
});
module.exports = router;
